﻿Imports System.IO
Partial Class WebForm_ManageWorkContent_SearchPlanHeader
    Inherits System.Web.UI.UserControl

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Me.BindDDLOrganization()
        End If
        ScriptManager.GetCurrent(Me.Page).RegisterPostBackControl(Me.gv)

        '只有管理人員才可以按次年例行服務計劃之產生
        If MyObj.IsSystem(clsAuth.GetUserID()) = False Then
            Me.btnAddNextPlan.Visible = False
        Else
            Me.btnAddNextPlan.Visible = True
        End If
    End Sub

    Protected Sub btnQuery_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnQuery.Click
        Me.BindGV()
    End Sub

    Protected Sub btnAddPlanItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddPlanItem.Click
        RaiseEvent Add(Me, New EventArgs)
    End Sub


    Public Sub BindGV()
        Dim dat As New clsData
        Dim sql As New MyOrganizationDataFilter(True)

        sql.Length = 0

        sql.AppendFormat(" select a.*, a.OrganizationID as UOrganizationID ,b.OrganizationName,(a.Year-1911) as tYear from ")
        sql.AppendFormat(" CleanPlanHeader a inner join OrganizationView b  ")
        sql.AppendFormat(" on a.OrganizationID = b.UOrganizationID ")
        sql.AppendFormat(" Where 1 = 1 ")

        If Me.AnnualControl1.Anaual <> "" Then
            sql.AppendFormat(" And a.Year=@Year ")
            sql.AddWithValue("Year", Me.AnnualControl1.Anaual)
        End If

        If Me.ddlOrganization.SelectedValue <> "" Then
            sql.AppendFormat(" And a.OrganizationID=@OrganizationID ")
            sql.AddWithValue("OrganizationID", Me.ddlOrganization.SelectedValue)
        End If

        sql.AppendFormat(" Order By A.Year ")

        Me.gv.DataSource = dat.GetData(sql)
        Me.gv.DataBind()

    End Sub

    Protected Sub gv_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gv.PageIndexChanging
        Me.gv.PageIndex = e.NewPageIndex
        Me.BindGV()
    End Sub

    Protected Sub gv_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv.RowCommand
        If e.CommandName = "MyEdit" Then
            Me.PlanHeaderID = e.CommandArgument.ToString()
            RaiseEvent Editing(Me, New EventArgs)
        ElseIf e.CommandName = "MyDownload" Then

            Dim dat As New clsData
            Dim sql As New MyStringBuilder

            sql.Length = 0

            sql.AppendFormat(" Select * From CleanPlanHeader ")
            sql.AppendFormat(" Where PlanHeaderID=@PlanHeaderID ")

            sql.AddWithValue("PlanHeaderID", e.CommandArgument.ToString())

            Dim dt As System.Data.DataTable = dat.GetData(sql)

            If dt.Rows.Count > 0 Then
                Dim FileInfo As New System.IO.FileInfo(Server.MapPath(dt.Rows(0)("FileUrl").ToString()))
                Me.Response.Clear()
                Me.Response.AddHeader("Content-Disposition", ("attachment;filename=" & Server.UrlPathEncode(dt.Rows(0)("FileName").ToString())))
                Me.Response.HeaderEncoding = System.Text.Encoding.GetEncoding("utf-8")
                Me.Response.AddHeader("Content-Length", FileInfo.Length.ToString())
                Me.Response.ContentType = "application/octet-stream"
                Me.Response.WriteFile(FileInfo.FullName)

                Me.Response.End()
            Else
                MyObj.ShowMessage("此計劃尚未上傳檔案")
            End If


        End If
    End Sub

    Protected Sub gv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gv.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim haveAccess As New MyBoolean

            haveAccess.Add(Not TypeOf DataBinder.Eval(e.Row.DataItem, "HaveAccess") Is DBNull AndAlso DataBinder.Eval(e.Row.DataItem, "HaveAccess") = "Y")
            '編輯按鈕權限
            If haveAccess.Value = True Then
                TryCast(e.Row.FindControl("lknEdit"), LinkButton).Visible = True
            Else
                TryCast(e.Row.FindControl("lknEdit"), LinkButton).Visible = False
            End If
            'If clsAuth.IsAdministrator() Then
            '    TryCast(e.Row.FindControl("lknEdit"), LinkButton).Visible = True
            'Else
            '    Dim uOrgID As String = CType(e.Row.FindControl("lblUOrganizationID"), Label).Text

            '    If uOrgID = clsAuth.GetUser().UOrganizationID Then

            '        'TryCast(e.Row.FindControl("mvForm"), MultiView).SetActiveView(TryCast(e.Row.FindControl("vwEdit"), View))
            '    Else

            '        'TryCast(e.Row.FindControl("mvForm"), MultiView).SetActiveView(TryCast(e.Row.FindControl("vwSelect"), View))
            '    End If
            'End If

        End If
    End Sub
    Protected Function GetServiceData(ByVal year As Integer) As Data.DataTable
        Dim sql As New MyStringBuilder
        Dim dat As New clsData

        sql.Length = 0

        sql.AppendFormat("Select * from CleanPlan where year(StartDate)='{0}' ", year)

        Return dat.GetData(sql)
    End Function
    Protected Function GetYearPlan(ByVal Year As Integer) As Data.DataTable
        Dim sql As New MyStringBuilder
        Dim dat As New clsData

        sql.Length = 0
        sql.AppendFormat(" Select * From CleanPlanHeader ")
        sql.AppendFormat(" Where Year = '{0}' ", Year)
        Return dat.GetData(sql)
    End Function
    Protected Sub btnAddNextPlan_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddNextPlan.Click
        Dim sql As New MyStringBuilder
        Dim dat As New clsData
        Dim filedt As Data.DataTable
        Dim ServiceDT As Data.DataTable
        ' Dim ServiceNextDT As Data.DataTable
        Dim ccdt As Data.DataTable
        Dim PlanID As String = ""
        Dim NowYear As Integer = DateTime.Now.Year
        Dim FileOldUrl As String = ""
        Dim FileNewUrl As String = ""
        '新增前先檢查 年度 是否已有計畫(每年度只能有一個計畫)

        If GetYearPlan(NowYear + 1).Rows.Count > 0 Then
            MyObj.ShowMessage(String.Format("{0}年度計畫已經產生", NowYear - 1911 + 1))
            Exit Sub
        End If


        '準備服務計畫資料
   
        filedt = GetYearPlan(NowYear)

        '準備服務資料

        ServiceDT = Me.GetServiceData(NowYear)
        '準備服務內容資料
        sql.Length = 0
        sql.AppendFormat("Select  cc.PlanID,cc.ItemGroup,cc.ItemValue from CleanPlan cp ")
        sql.AppendFormat("inner join CleanPlanContent cc on cp.PlanID=cc.PlanID ")
        sql.AppendFormat("where year(cp.StartDate)='{0}' ", NowYear)
        ccdt = dat.GetData(sql)




        sql.Length = 0
        For i As Integer = 0 To filedt.Rows.Count - 1
            FileOldUrl = filedt.Rows(i)("FileUrl").ToString()
            FileNewUrl = "~/Downloads/ClanPlanHeader/" + Guid.NewGuid().ToString() + DateTime.Today.ToString("yyyyMMdd") + "." + FileOldUrl.Split(".")(1)
            '複製檔案
            File.Copy(Server.MapPath(FileOldUrl), Server.MapPath(FileNewUrl), False)

            sql.AppendFormat("Insert Into CleanPlanHeader([Year],OrganizationID,PersonInCharge,[Subject],[FileName],FileUrl,CreateBy,CreateDate,UpdateBy,UpdateDate) ")
            sql.AppendFormat(" select ")
            sql.AppendFormat("'{0}', ", Int32.Parse(filedt.Rows(i)("Year").ToString()) + 1)
            sql.AppendFormat("'{0}', ", filedt.Rows(i)("OrganizationID").ToString())
            sql.AppendFormat("'{0}', ", filedt.Rows(i)("PersonInCharge").ToString())
            sql.AppendFormat("'{0}', ", "")
            sql.AppendFormat("'{0}', ", Date.Today.ToString("yyyy/MM/dd") & "_" & filedt.Rows(i)("FileName").ToString())
            sql.AppendFormat("'{0}', ", FileNewUrl)
            sql.AppendFormat("'{0}', ", clsAuth.GetUserID())
            sql.AppendFormat("{0}, ", "getdate()")
            sql.AppendFormat("'{0}', ", clsAuth.GetUserID())
            sql.AppendFormat("{0}; ", "getdate()")
        Next
        Try
            ' MyObj.WriteLog(sql.ToString())
            dat.AccData(sql)
        Catch ex As Exception
            MyObj.ShowMessage(ex.Message)
            Exit Sub
        End Try



        Using scope As New Transactions.TransactionScope

            For j As Integer = 0 To ServiceDT.Rows.Count - 1
                sql.Length = 0
                sql.AppendFormat("insert CleanPlan (PlanHeaderID,ItemType,PlanName,UOrganizationID,OrganizationTel,Location,RegionType,PersonInCharge ")
                sql.AppendFormat(",StartDate,EndDate,IsPublic,CreateDate,CreateBy) Select ")
                sql.AppendFormat(" '{0}' ", ServiceDT.Rows(j)("PlanHeaderID").ToString())
                sql.AppendFormat(",'{0}' ", ServiceDT.Rows(j)("ItemType").ToString())
                sql.AppendFormat(",'{0}' ", DateTime.Today.ToString("yyyy/MM/dd") & "_" & ServiceDT.Rows(j)("PlanName").ToString())
                sql.AppendFormat(",'{0}' ", ServiceDT.Rows(j)("UOrganizationID").ToString())
                sql.AppendFormat(",'{0}' ", ServiceDT.Rows(j)("OrganizationTel").ToString())
                sql.AppendFormat(",'{0}' ", ServiceDT.Rows(j)("Location").ToString())
                sql.AppendFormat(",'{0}' ", ServiceDT.Rows(j)("RegionType").ToString())
                sql.AppendFormat(",'{0}' ", ServiceDT.Rows(j)("PersonInCharge").ToString())
                sql.AppendFormat(",'{0:yyyy/MM/dd}' ", DateTime.Parse(ServiceDT.Rows(j)("StartDate").ToString()).AddYears(1))
                sql.AppendFormat(",'{0:yyyy/MM/dd}' ", DateTime.Parse(ServiceDT.Rows(j)("EndDate").ToString()).AddYears(1))
                sql.AppendFormat(",'{0}' ", ServiceDT.Rows(j)("IsPublic").ToString())
                sql.AppendFormat(",{0} ", "getdate()")
                sql.AppendFormat(",'{0}'; ", clsAuth.GetUserID())
                Try
                    '  MyObj.WriteLog(sql.ToString())
                    dat.AccData(sql)
                Catch ex As Exception
                    MyObj.ShowMessage(ex.Message)
                    Exit Sub
                End Try

                '準備服務項目的PlanHeaderID
                Dim phID As String
                phID = ""
                sql.Length = 0
                sql.AppendFormat("Select PlanHeaderID From CleanPlanHeader Where Year='{0}' ", NowYear + 1)
                sql.AppendFormat("and OrganizationID='{0}' ", ServiceDT.Rows(j)("UOrganizationID").ToString())
                phID = dat.GetSingleData(sql.ToString, Nothing, Data.CommandType.Text)

                sql.Length = 0
                sql.AppendFormat("update CleanPlan set ")
                sql.AppendFormat("PlanHeaderID = '{0}' ", phID)
                sql.AppendFormat("where UOrganizationID='{0}' ", ServiceDT.Rows(j)("UOrganizationID").ToString())
                sql.AppendFormat("and year(StartDate)='{0}' ", NowYear + 1)
                Try
                    '  MyObj.WriteLog(sql.ToString())
                    dat.AccData(sql)
                Catch ex As Exception
                    MyObj.ShowMessage(ex.Message)
                    Exit Sub
                End Try

                PlanID = MyObj.GetIdentity()
                sql.Length = 0
                sql.AppendFormat(" Insert Into CleanPlanContent(PlanID,ItemGroup,ItemValue)  Select ")
                sql.AppendFormat(" {0} ", PlanID)
                sql.AppendFormat(" ,c.ItemGroup ")
                sql.AppendFormat(" ,c.ItemValue ")
                sql.AppendFormat("From CleanPlanContent c ")
                sql.AppendFormat("Where c.PlanID ={0};  ", ServiceDT.Rows(j)("PlanID").ToString())

                '
                'dt = GetServiceContent(ServiceDT.Rows(j)("PlanID").ToString())
                Try
                    ' MyObj.WriteLog(sql.ToString())
                    dat.AccData(sql)
                Catch ex As Exception
                    MyObj.ShowMessage(ex.Message)
                    Exit Sub
                End Try



            Next
            scope.Complete()
        End Using
        If sql.Length > 0 Then
            MyObj.ShowMessage(String.Format("{0}年度計畫及項目產生成功!", NowYear - 1911 + 1))
        Else
            MyObj.ShowMessage(String.Format("{0}年度計畫及項目產生失敗!", NowYear - 1911 + 1))
        End If


    End Sub

End Class

Partial Class WebForm_ManageWorkContent_SearchPlanHeader

#Region "事件"
    Public Event Add(ByVal source As Object, ByVal e As EventArgs)
    Public Event Editing(ByVal source As Object, ByVal e As EventArgs)
#End Region

#Region "繫結資料"
    Private Sub BindDDLOrganization()
        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        sql.AppendFormat("select o.* ")
        sql.AppendFormat("from OrganizationView o ")
        sql.AppendFormat("where OrganizationName like '%公所%' and Active = 'Y' ")

        Me.ddlOrganization.DataTextField = "OrganizationName"
        Me.ddlOrganization.DataValueField = "UOrganizationID"
        Me.ddlOrganization.DataSource = MyObj.GetDDLDirectOrganizationData()
        Me.ddlOrganization.DataBind()

        If Me.ddlOrganization.Items.Count > 1 Then
            Me.ddlOrganization.Items.Insert(0, MyObj.GetDDLSelectAllItem())
        End If

    End Sub
#End Region

#Region "屬性"
    Public Property PlanHeaderID() As String
        Get
            Return ViewState("SelectedPlanHeaderID")
        End Get
        Set(ByVal value As String)
            ViewState("SelectedPlanHeaderID") = value
        End Set
    End Property
#End Region


End Class
